package xyh

import (
	"encoding/json"
	"fmt"
	"net/url"
	"time"
)

// 获取 access_token
func RefreshAccessToken() (*string, error) {
	var data *AccessToken
	if cacheData, found := cache.Get("auth"); found {
		data = cacheData.(*AccessToken)
		return &data.Data.AccessToken, nil
	}

	params := url.Values{}
	params.Add("clientId", Conf.ClientID)
	params.Add("clientSecret", Conf.ClientSecret)
	params.Add("grantType", "client_credentials")
	params.Add("responseType", "token")

	payload, err := httpRequest("oauth2/token", params, nil)
	if err != nil {
		return nil, err
	}

	if err := json.Unmarshal(*payload, &data); err != nil {
		return nil, err
	}
	if data.Code != 0 {
		return nil, fmt.Errorf(data.Msg)
	}

	if data.Data.AccessToken != "" {
		cache.Set("auth", data, time.Duration(data.Data.ExpiresIn-20)*time.Second)
	}
	return &data.Data.AccessToken, nil
}
